package indigo.ueditor.handler;

import java.io.ByteArrayInputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.google.common.collect.Maps;
import com.google.common.io.BaseEncoding;
import com.google.common.io.Files;

import indigo.ueditor.PathPatternResolver;
import indigo.ueditor.UEditorFileManager;
import indigo.ueditor.UEditorHandler;
import indigo.ueditor.UEditorState;

public class Base64UploadHandler implements UEditorHandler {
	private final String name;
	private final UEditorFileManager fileManager;
	private final String parameterName;
	private final String savePathPattern;
	private final String fileName;
	private final long maxSize;

	public Base64UploadHandler(String name, UEditorFileManager fileManager,
			String parameterName, String savePathPattern, String fileName, long maxSize) {
		this.name = name;
		this.fileManager = fileManager;
		this.parameterName = parameterName;
		this.savePathPattern = savePathPattern;
		this.fileName = fileName;
		this.maxSize = maxSize;
	}

	@Override
	public String getName() {
		return name;
	}

	@Override
	public Object handle(HttpServletRequest request) {
		String base64Text = request.getParameter(parameterName);
		byte[] data = BaseEncoding.base64().decode(base64Text);

		String fileExtension = Files.getFileExtension(fileName);
		String fileSuffix = fileExtension.isEmpty() ? "" : "." + fileExtension;

		PathPatternResolver resolver = new PathPatternResolver();
		resolver.putVariable("filename", fileName);
		String savePath = resolver.resolve(savePathPattern) + fileSuffix;

		fileManager.createFile(savePath, new ByteArrayInputStream(data), maxSize);

		Map<String, Object> resultMap = Maps.newHashMap();
		resultMap.put("state", UEditorState.SUCCESS.getMessage());
		resultMap.put("url", savePath);
		resultMap.put("type", fileSuffix);
		resultMap.put("original", "");
		return resultMap;
	}
}
